<?php
namespace Model\Outlanderp4la;

use Hoa\Registry\Registry;
use Library\Db;
use Library\Log;
use Model\BaseModel;



class DynCnfModel extends BaseModel {
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct();
	}


	/**
	 * test
	 * @return string
	 */
	static public function test() {
		return __METHOD__;
	}


	/**
	 * 通过类型和键，查询配置项
	 * @param string $type
	 * @param string $k
	 */
	static public function getDynCnfByTypeAndK ($type, $k) {
		$conf = Registry::get('conf');
		$dbConf = $conf['database']['outlanderp4la'];
		$db = new Db($dbConf);
		$dynCnf = $db->where('type', $type)->where('k', $k)->getOne('dyn_cnf');
		return $dynCnf;
	}


	/**
	 * 查询用于skusystem api调用的sku更新时间，如果不存在，则创建该动态配置项
	 */
	static public function getSkusystemSkuUpdatedAt4Outlanderp4la() {
		$type = 'skusystem';
		$k = 'sku_update_at';
		$dynCnf = self::getDynCnfByTypeAndK($type, $k);
		if (!$dynCnf) {
			$now = date('Y-m-d H:i:s');
			$dynCnf = [
				'type' => $type,
				'k' => $k,
				'v' => '0000-00-00 00:00:00',
				'remark' => '用于skusystem api调用的sku更新时间',
				'create_at' => $now,
				'update_at' => $now,
			];
			self::addDynCnf($dynCnf);
		}
		return $dynCnf;
	}


	/**
	 * 添加单个配置项
	 * @param array $data
	 * @return int
	 */
	static public function addDynCnf($data) {
		//定义变量
		$conf = Registry::get('conf');
		$dbConf = $conf['database']['outlanderp4la'];
		$db = new Db($dbConf);
		$now = date('Y-m-d H:i:s');

		//整理配置项
		$data['create_at'] = $now;
		$data['update_at'] = $now;

		//写入数据库
		$id = $db->insert('dyn_cnf', $data);

		//Success
		return $id;
	}


	/**
	 * 保存配置项
	 * @param array $data
	 * @param int $id
	 * @return int
	 */
	static public function saveDynCnf($data, $id) {
		//定义变量
		$conf = Registry::get('conf');
		$dbConf = $conf['database']['outlanderp4la'];
		$db = new Db($dbConf);
		$now = date('Y-m-d H:i:s');

		//检验参数
		$data['update_at'] = $now;

		//保存
		$db->where('id', $id);
		$result = $db->update('dyn_cnf', $data);
		return $result;
	}


}